window.onload = function () {
    // 就餐方式切换
    var dining = document.querySelector('.dining')
    var mode = dining.children[0].innerText
    dining.onclick = e => {
        var target = e.target
        if (target.tagName === 'SPAN') {
            for (var a = 0; a < dining.children.length; a++) {
                dining.children[a].className = ''
            }
            target.className = 'active'
            mode = target.innerText
        }
    }

    // 支付
    var topay = document.querySelector('.topay')
    topay.onclick = function () {
        // location.href = './order.html'
        // 发请求生成订单
        request({
            url: '/front/api/order/create',
            method: 'post',
            data: {
                eatWay: mode,
                totalPrice: document.querySelector('.totalprice').innerText.replace('￥', ''),
                userId: getCookie('userId'),
                cartIds: this.dataset.cartids,
                dishName: document.querySelector('.cartlist .name b').innerText
            },
            headers: {
                Authorization: localStorage.getItem('token')
            }
        }).then(res => {
            // console.log(res)
            let { error_code, msg } = res
            if (error_code === 200) {
                location.href = './order.html'
            }
        })
    }

    // 获取放购物车数据的标签
    let cartlist = document.querySelector('.cartlist')
    // 发送请求获取购物车的数据
    request({
        url: '/front/api/cart/getall/' + getCookie('userId'),
        headers: {
            Authorization: localStorage.getItem('token')
        }
    }).then(res => {
        // console.log(res);
        let { error_code, msg } = res
        if (error_code === 200) {
            // 定义总价初始为0
            let totalPrice = 0
            let cartids = ''
            res.data.carts.forEach(cart => {
                cartids += ',' + cart._id
                let speandkind = cart.speandkind.replace(/￥[0-9\.]+/, '')
                speandkind = speandkind.replace('=====', ',')
                cartlist.innerHTML += `
                    <div>
                        <img src="${cart.dish.imgpath}" alt="">
                        <div class="name">
                            <b>${cart.dish.name}</b>
                            <br>
                            <span>${speandkind}</span>
                        </div>
                        <div class="number">x${cart.number}</div>
                        <div class="price">￥${cart.dish.price}</div>
                    </div>
                `
                // 计算总价
                totalPrice += cart.number * cart.dish.price
            })
            topay.setAttribute('data-cartids', cartids.slice(1))
            // 将总价放在标签中
            document.querySelector('.totalprice').innerText = '￥' + totalPrice.toFixed(2)
            document.querySelector('.totalprice1').innerText = '￥' + totalPrice.toFixed(2)
        }
    })

}